/*
 * AppID.cpp
 *
 *  Created on: 2018年10月24日
 *      Author: zhengboyuan
 */

#include "stdafx.h"
#include "AppID.h"
#include "TStringUtil.h"


size_t AppID::MAX_ID = 128;


AppID::AppID(const char* prefix):
        m_id(),
        m_name(),
        m_prefix(prefix),
        m_handle()
{
}

AppID::~AppID()
{
    cleanup();
}

void AppID::setPrefix(const std::string& prefix)
{
    m_prefix = prefix;
}

size_t AppID::getID()
{
    return m_id;
}

std::string AppID::getName()
{
    return m_name;
}

void AppID::reset()
{
	makeID(m_id, m_name);
}

bool AppID::makeID(size_t& id, std::string& name)
{
    cleanup();

    for (size_t i = 0; i < MAX_ID; i ++)
    {
        std::string str = comn::StringUtil::format("%s_%d", m_prefix.c_str(), i);
        HANDLE handle = CreateMutexA(NULL, true, str.c_str());
		if (GetLastError() == ERROR_ALREADY_EXISTS)
		{
			CloseHandle(handle);
			handle = NULL;
		}
		else
        {
            m_handle = handle;
            id = i;
            name = str;
            return true;
        }
    }
    return false;
}

void AppID::cleanup()
{
    if (!m_handle)
    {
        return;
    }

    ReleaseMutex(m_handle);
    CloseHandle(m_handle);
    m_handle = NULL;

    m_id = 0;
    m_name.clear();
}
